package com.game.view;

import com.game.entity.User;
import com.game.service.UserService;
import lombok.Data;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 登陆页面
 */
@Data
public class LoginPanel extends JPanel {
    private JFrame frame ;
    private JTextField userField ; // 文本框的对象
    private JPasswordField pwdField; // 密码框的对象
    private JButton button ; // 登陆按钮对象
    private String message ;
    private UserService userService ; // 声明用户服务

    public  LoginPanel (){
        userService = new UserService();
        message = "";   // 您输入的用户名和密码错误,请重新输入
        // 初始化变量
        userField = new JTextField();
        pwdField = new JPasswordField();
        button = new JButton();
        // 设置相关属性
        userField.setBounds(200,100,150,30);
        pwdField.setBounds(200,150,150,30);
        button.setBounds(200,250,100,50);
        button.setText("登陆");
        // 设置自由定位布局
        this.setLayout(null);
        // 画板添加对象
        this.add(userField);
        this.add(pwdField);
        this.add(button);

        // 添加 button的监听
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 调用服务层, 实现业务逻辑
                User user = new User();
                user.setName(userField.getText());
                user.setPassword(pwdField.getText());
                message = userService.login(user);  // 服务层实现返回字符串
                LoginPanel.this.repaint();
                if(message == "登陆成功"){
                    CardLayout layout = (CardLayout) frame.getContentPane().getLayout();
                    layout.show(frame.getContentPane(),"gamePanel");
                }

            }
        });

    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0,0,800,600);
        g.setColor(Color.RED);
        g.drawString(message,350,150);


        // 因为swing组件加载多组件时,
        // 会遇到刷新不到位的情况。所以画板画完内容后,需要将添加的组件再次画出来。
        userField.repaint();
        pwdField.repaint();
        button.repaint();
    }
}
